<template>
  <div class="main" style="height: 824px">
    <div style="margin: 5px">
      <el-input v-model="ino" placeholder="请输入采购编号" :suffix-icon="Search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-input v-model="eno" placeholder="请输入员工编号" :suffix-icon="Search" style="width: 200px; margin-left: 5px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="danger" style="margin-left: 5px" @click="resetParam">重置</el-button>
      <el-button type="success" style="margin-left: 5px" @click="add" :disabled="user.roleLevel === 2">新增</el-button>
      <el-button type="info" style="margin-left: 5px" @click="exportCsv">导出为CSV文件</el-button>
    </div>
    <el-table :data="tableData" :header-cell-style="{ background: '#f3f6fd', color: '#555' }" :border="true">
      <el-table-column prop="ino" label="采购清单号"></el-table-column>
      <el-table-column prop="eno" label="员工编号"></el-table-column>
      <el-table-column prop="inum" label="采购数量"></el-table-column>
      <el-table-column prop="iprice" label="采购总价"></el-table-column>
      <el-table-column :formatter="formatDate" prop="itime" label="采购时间"></el-table-column>
      <el-table-column prop="iremark" label="备注"></el-table-column>
      <el-table-column prop="" label="操作">
        <template v-slot:default="scope">
          <el-button size="small" type="success" @click="edit(scope.row)" :disabled="user.roleLevel === 2">编辑</el-button>
          <el-popconfirm title="你确定要删除这个吗?" @confirm="del(scope.row.ino)">
            <template #reference>
              <el-button size="small" type="danger" :disabled="user.roleLevel === 2">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[17]" :small="small"
                   :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   style="bottom: 20px; position: fixed; margin-left: 5px; z-index: 2"/>
    <el-dialog class="el-dialog" v-model="centerDialogVisible" :title="title" width="400px" center @close="resetForm">
      <el-form :model="form" label-width="auto" style="width: 80%; margin-left: 40px;" :rules="rules"
               ref="formRef">
        <el-form-item label="采购编号" prop="ino">
          <el-input :disabled="title === '编辑'" v-model="form.ino"/>
        </el-form-item>
        <el-form-item label="员工编号" prop="eno">
          <el-input v-model="form.eno"/>
        </el-form-item>
        <el-form-item label="采购数量" prop="inum">
          <el-input-number v-model="form.inum" :min="1" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="采购时间" prop="itime">
          <el-date-picker
              v-model="form.itime"
              type="datetime"
              placeholder="选择时间"
              format="YYYY/MM/DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注" prop="iremark">
          <el-input type="textarea" v-model="form.iremark"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="centerDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="resetFormEditAdd">重置</el-button>
          <el-button type="success" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onBeforeMount, ref} from 'vue';
import axios from 'axios';
import {httpUrl} from '../../main.js';
import {Search} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import Papa from "papaparse";

const user = ref(JSON.parse(sessionStorage.getItem("CurUser")));
const currentPage = ref(1);
const pageSize = ref(17);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref(0);
const tableData = ref();
const ino = ref('');
const eno = ref('')
const inoCompare = ref();
const centerDialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  ino: "",
  eno: "",
  inum: 1,
  iprice: 0.00,
  itime: null,
  iremark: ""
});

const formatDate = (row, column) => {
  // 获取单元格数据
  const data = row[column.property];
  if (data == null) {
    return null;
  }
  const dt = new Date(data);
  return `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()} ${dt.getHours()}:${dt.getMinutes()}:${dt.getSeconds()}`;
};

const resetFormEditAdd = function () {
  if (title.value === "新建") {
    form.value.ino = ""
  }
  form.value.eno = ""
  form.value.inum = 1
  form.value.iprice = 0.00
  form.value.itime = null
  form.value.iremark = ""
}

const resetForm = function () {
  form.value.ino = ""
  form.value.eno = ""
  form.value.inum = 1
  form.value.iprice = 0.00
  form.value.itime = null
  form.value.iremark = ""
  // formRef.value.resetFields()
}
const rules = ref({
  ino: [
    {required: true, message: '请输入编号', trigger: 'blur'},
    {max: 10, message: '编号长度不能大于10字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.ino) {
          if (title.value === "新增") {
            try {
              axios.get(httpUrl + '/inbuy/findByNo?ino=' + form.value.ino).then((res) => res.data).then((res) => {
                console.log(res);
                if (res.code != 200) {
                  callback()
                } else {
                  callback(new Error("编号已存在"))
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          if (title.value === "编辑") {
            if (inoCompare.value === form.value.ino) {
              console.log(ino.value)
              callback()
            } else {
              try {
                axios.get(httpUrl + '/inbuy/findByNo?ino=' + form.value.ino).then((res) => res.data).then((res) => {
                  console.log(res);
                  if (res.code != 200) {
                    callback()
                  } else {
                    callback(new Error("账号已存在"))
                  }
                });
              } catch (error) {
                console.log(error);
              }
            }
          }
        }
      }, trigger: 'blur'
    }
  ],
  eno: [
    {required: true, message: '请输入编号', trigger: 'blur'},
    {max: 10, message: '编号长度不能大于10字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.eno) {
          try {
            axios.get(httpUrl + '/employee/findByNo?eno=' + form.value.eno).then((res) => res.data).then((res) => {
              console.log(res);
              if (res.code == 200) {
                callback()
              } else {
                callback(new Error("编号不存在"))
              }
            });
          } catch (error) {
            console.log(error);
          }
        }
      }, trigger: 'blur'
    }
  ],
  inum: [
    {type: "number", message: '采购数量必须是一个整数', trigger: 'blur'},
  ],
  iremark: [
    {max: 1000, message: '不能超过1000个字符', trigger: 'blur'},
  ]
});
const title = ref('')

const handleSizeChange = (val) => {
  console.log(`每页${val}条`);
  currentPage.value = 1;
  pageSize.value = val;
  loadPost();
};

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
  loadPost();
};

const resetParam = () => {
  currentPage.value = 1;
  ino.value = '';
  eno.value = ''
  loadPost();
};

const add = () => {
  title.value = "新增"
  centerDialogVisible.value = true;
};

const doSave = function () {
  try {
    axios.post(httpUrl + '/inbuy/save', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '新增成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('新增失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const doMod = function () {
  try {
    axios.post(httpUrl + '/inbuy/update', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('编辑失败');
        centerDialogVisible.value = false;
      }
    });
    axios.post(httpUrl + '/details/listI', {
      ino: form.value.ino,
    }).then((res) => {
      console.log(res);
      axios.post(httpUrl + '/details/updateBatch', res.data).then((res) => res.data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          ElMessage({
            message: '级联修改成功',
            type: 'success'
          })
        }else {
          ElMessage.error('级联修改失败');
        }
      })
    });
  } catch (error) {
    console.log(error);
  }
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证成功');
      if (title.value === "编辑") {
        doMod()
      } else {
        doSave()
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
    resetForm()
  });
};

const edit = function (row) {
  console.log(row)
  inoCompare.value = row.ino
  form.value.ino = row.ino
  form.value.eno = row.eno
  form.value.inum = row.inum
  form.value.iprice = row.iprice
  form.value.itime = row.itime
  form.value.iremark = row.iremark
  title.value = "编辑"
  centerDialogVisible.value = true;
}

const del = function (ino) {
  console.log(ino)
  try {
    axios.get(httpUrl + '/inbuy/delete?ino=' + ino).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        });
        loadPost()
      } else {
        ElMessage.error('删除失败');
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const loadGet = async () => {
  try {
    axios.get(httpUrl + '/inbuy/list').then((res) => res.data).then((res) => {
      console.log(res);
      tableData.value = res;
    });
  } catch (error) {
    console.log(error);
  }
};

const loadPost = async () => {
  try {
    axios.post(httpUrl + '/inbuy/listPage', {
      pageSize: pageSize.value,
      pageNum: currentPage.value,
      param: {
        ino: ino.value,
        eno: eno.value
      }
    }).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        tableData.value = res.data;
        total.value = res.total;
      } else {
        alert('获取数据失败');
      }
    });
  } catch (error) {
    console.log(error);
  }
};
const exportCsv = () => {
  const header = { 'ino': '采购清单号', 'eno': '员工编号', 'inum': '采购数量', 'iprice': '采购总价', 'itime': '采购时间', 'iremark': '采购备注'};
  export_csv(header, tableData.value);

  function export_csv(header, data) {
    let list = [];
    for (let i in data) {
      let item = data[i];
      let obj = {};
      for (let key in header) {
        let title = header[key];
        let value = item[key];
        obj[title] = value;
      }
      list.push(obj);
    }

    var csv = Papa.unparse(list);
    let content = new Blob(['\uFEFF' + csv]);
    let urlObject = window.URL || window.webkitURL || window;
    let url = urlObject.createObjectURL(content);
    let el = document.createElement("a");
    el.href = url;
    el.download = "采购主表.csv";
    el.click();
    urlObject.revokeObjectURL(url);
  }
};
onBeforeMount(async () => {
  await loadPost();
});
</script>

<style scoped>
.el-dialog {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
